package ls.jpa.chapter7.service;

import ls.jpa.chapter7.entity.Person;
import ls.jpa.chapter7.repository.PersonRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoOperations;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;

/**
 * @author Barudisshu
 */
@Service
public class PersonService {

    @Autowired
    private PersonRepository personRepository;


    public Person findByName(String name) {
        return personRepository.findByName(name);
    }

    public List<Person> findAll() {
        return personRepository.findAll();
    }

    public List<Person> findBySex(boolean sex) {
        return personRepository.findBySex(sex);
    }

    public Person save(Person person) {
        return personRepository.save(person);
    }

    /**
     * 自定义Id增长方案
     * @param step 步长
     * @return 新的字段
     */
    public int autoIncrement(int step) {

        List<Person> personList = findAll();
        Set<Integer> hashSet = new HashSet<>();

        for (Person person : personList) {
            hashSet.add(person.getId());
        }

        TreeSet<Integer> treeSet = new TreeSet<>(hashSet);

        if (treeSet.isEmpty()) {
            return 1;
        } else {
            return treeSet.last()+step;
        }
    }
}
